//
//  PMMerchantManagerView.m
//  Manager
//
//  Created by lvzhao on 2020/8/1.
//  Copyright © 2020 吕VV. All rights reserved.
//

#import "PMMerchantManagerView.h"
#import "PMMerchantManagerViewModel.h"
#import "LZTableSlideView.h"
#import "LZSortButton.h"
#import "LZMJDIYRefreshHeader.h"
#import "LZMJDIYRefeshFooter.h"
#import "LZOptionModel.h"
#import "PMScreenDownView.h"
#import "PMEditMerchantViewController.h"
#import "PMSettingRateViewController.h"


@interface PMMerchantManagerView()

@property (nonatomic,strong) LZTableSlideView *tableView;

@property (nonatomic,strong) PMMerchantManagerViewModel *viewModel;

@end

@implementation PMMerchantManagerView
- (instancetype)initViewModel:(LZBaseViewModel *)viewModel
{
    self = [super initViewModel:viewModel];
    if (self) {
        self.viewModel = (PMMerchantManagerViewModel *)viewModel;
        
        [self setupUI];
        
        [self reloadRightItem];
    
    }
    return self;
}

//刷新右按钮
- (void)reloadRightItem{
    
    ///!!!:筛选
    UIButton *screeningBtn = [UIButton lz_buttonImageName:@"pm_shaixuan" backgroundImageName:@""];
    screeningBtn.frame = CGRectMake(0, 0, 44, 44);
    [LZTool.currentViewController initBarItem:screeningBtn withType:1];
    [screeningBtn addTarget:self action:@selector(screenClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)setupUI{
    
    ///!!!:操作按钮
    UIView *optionView = [[UIView alloc] init];
    optionView.backgroundColor = UIColor.whiteColor;
    [self addSubview:optionView];
    [optionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(K_Device_Is_iPhoneX ? -34 : 0);
        make.height.mas_equalTo(50);
    }];
    
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = COLOR_cellLine;
    [optionView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.height.mas_equalTo(0.5);
    }];
    
    @weakify(self);
    CGFloat titleW = (K_SCREENWIDTH - 30)/1.0;
    NSArray *titles = @[@"进件开户"];
    UIView *lastView = nil;
    for (int i = 0; i < titles.count; i++){
        UIButton *optionBtn = [UIButton lz_buttonTitle:titles[i] titleColor:COLOR_appColor fontSize:15];
        [optionView addSubview:optionBtn];
        [optionBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(15);
            make.width.mas_equalTo(titleW);
            make.height.mas_equalTo(50);
            make.top.mas_equalTo(0);
        }];
        
       
        lastView = optionBtn;

        [[optionBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            
            RACSubject *subject = [RACSubject subject];
            PMEditMerchantViewController *editMerchantVC = [[PMEditMerchantViewController alloc] init];
            editMerchantVC.subject = subject;
            [LZTool.currentViewController.navigationController pushViewController:editMerchantVC animated:YES];
            [subject subscribeNext:^(id  _Nullable x) {
                @strongify(self);
                [self.viewModel getMerchantList:YES];
            }];
        }];
        
        
    }
    [self addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(0);
        make.width.mas_equalTo(kScreenWidth);
        make.bottom.mas_equalTo(optionView.mas_top);
    }];
    
    ///上拉加载. 下拉刷新
    [self addRefresh];

    [self.tableView setCallBlock:^(PMTouchTable touchTable, NSInteger index, LZSortButton * _Nullable sortBtn) {
        
        @strongify(self);
        switch (touchTable) {
            case PMTouchTableRight:
                [self selectTableIndex:index];
                break;

            default:
                break;
        }
   
    }];
    
    [self.viewModel.reloadSubject subscribeNext:^(id  _Nullable x) {
           dismiss(nil);
           @strongify(self);
           [self reloadTable:[x intValue]];
       }];
       
    
    
    showLoadingTitle(@"", nil);
    [self.viewModel getMerchantList:YES];
    
}

//筛选
- (void)screenClick:(UIButton *)sender{
    

    NSMutableArray *audiStatus = [LZOptionModel createOptionModel:@[@"待审核",@"审核中",@"审核通过",@"审核未通过",@"已禁用"] details:@[@"WAIT",@"AUDIT",@"NORMAL",@"REGJECT",@"CLOSE"] key:@"status"];
    
    NSArray *subSelectTitles = @[];
    NSArray *subTitles = @[];
    NSArray *placeholders = @[];

    subSelectTitles = @[@[],audiStatus];
    subTitles = @[@"关键字：",@"审核状态："];
    placeholders = @[@"公司名称/商户号",@"审核状态"];
    
    @weakify(self);
    [PMScreenDownView showScreenAlertType:LZAlertTypeTradeScreen cancel:@"重置" sure:@"确定" objectDict:@{@"subTitles":subTitles,@"subSelectTitles":subSelectTitles,@"placeholders":placeholders} cancelBlock:^(id  _Nullable object) {
        @strongify(self);
        [self.viewModel.paramsDictionary removeAllObjects];
    } sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithDictionary:object];
        [self.viewModel.paramsDictionary addEntriesFromDictionary:dataDictionary];
        showLoadingTitle(@"", nil);
        [self.viewModel getMerchantList:YES];
        
    }];

}

///刷线表格
- (void)reloadTable:(NSInteger) type{
    
    if(type > 3)return;
    
    self.tableView.dataModel = self.viewModel.dataModel;
    [self.tableView.rightTableView.mj_header endRefreshing];
    [self.tableView.rightTableView.mj_footer endRefreshing];
    self.tableView.rightTableView.mj_footer.hidden = NO;
    [self.tableView  dismissEmptyView];
    switch (type) {
        case 0:{
            self.tableView.rightTableView.mj_footer.hidden = YES;
        }
            break;
        default:
            break;
    }
    
    if(self.viewModel.dataModel.dataArray.count == 0){
        self.tableView.rightTableView.mj_footer.hidden = YES;
        [self.tableView tableViewDisplayWithImgName:@"no_data" message:@"暂无数据" contentoffsetY:100 showEmptyView:YES];
    }
}

///添加下拉, 上啦
- (void)addRefresh{
    
    @weakify(self);
    self.tableView.rightTableView.mj_header = [LZMJDIYRefreshHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        @strongify(self);
        [self.viewModel getMerchantList:YES];
 
    }];
    self.tableView.rightTableView.mj_footer = [LZMJDIYRefeshFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        @strongify(self);
        [self.viewModel getMerchantList:NO];
     
    }];
    
    // 不让mj 自适应宽度
    self.tableView.rightTableView.mj_header.autoresizingMask = UIViewAutoresizingNone;
    self.tableView.rightTableView.mj_header.mj_x = -self.viewModel.dataModel.leftWidth;
    // 设置mj宽度
    self.tableView.rightTableView.mj_header.mj_w = K_SCREENWIDTH;
    self.tableView.rightTableView.mj_footer.autoresizingMask = UIViewAutoresizingNone;
    self.tableView.rightTableView.mj_footer.mj_w = K_SCREENWIDTH ;
    self.tableView.rightTableView.mj_footer.mj_x = -self.viewModel.dataModel.leftWidth;
    
}


///选择第几行操作
- (void)selectTableIndex:(NSInteger) index{
    
    PMMerchantManagerModel *merchantModel = self.viewModel.dataArray[index];
    
    NSMutableArray *subTitles = [[NSMutableArray alloc] init];

    [subTitles addObject:@"修改资料"];
    [subTitles addObject:@"商户审核"];
    [subTitles addObject:@"设置费率"];
    [subTitles addObject:@"禁用/启用"];
    [subTitles addObject:@"删除"];
    [subTitles addObject:@"更新余额"];
    [subTitles addObject:@"- 余额扣划"];
    [subTitles addObject:@"- 余额冻结"];
    [subTitles addObject:@"+ 金额解冻"];
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeActionSheet withTitle:@"" message:@"" cancel:@"取消" sure:@"" objectDict:@{@"subTitles":subTitles} cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
    
        NSString *subtitle = subTitles[[object intValue]];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self);
            if([subtitle isEqualToString:@"修改资料"]){
                RACSubject *subject = [RACSubject subject];
                PMEditMerchantViewController *editMerchantVC = [[PMEditMerchantViewController alloc] init];
                editMerchantVC.subject = subject;
                editMerchantVC.merchantModel = merchantModel;
                [LZTool.currentViewController.navigationController pushViewController:editMerchantVC animated:YES];
                [subject subscribeNext:^(id  _Nullable x) {
                    @strongify(self);
                    [self.viewModel getMerchantList:YES];
                }];
            } else if([subtitle containsString:@"商户审核"]){
                [self audiMerchantModel:merchantModel];
            } else if([subtitle containsString:@"禁用/启用"]){
                [self disableMerchantModel:merchantModel];
            } else if([subtitle containsString:@"删除"]){
                [self deleteMerchantModel:merchantModel];
            } else if([subtitle containsString:@"更新余额"]){
                [self updateAmountMerchantModel:merchantModel];
            } else if([subtitle containsString:@"设置费率"]){
            
                RACSubject *subject = [RACSubject subject];
                PMSettingRateViewController *settingRateVC = [[PMSettingRateViewController alloc] init];
                settingRateVC.subject = subject;
                settingRateVC.merchantModel = merchantModel;
                [LZTool.currentViewController.navigationController pushViewController:settingRateVC animated:YES];
                [subject subscribeNext:^(id  _Nullable x) {
                    @strongify(self);
                    [self.viewModel getMerchantList:YES];
                }];
                
            } else if([subtitle containsString:@"余额扣划"]){
                [self transferAmountMerchantModel:merchantModel type:@"deduct"];
            } else if([subtitle containsString:@"余额冻结"]){
                [self transferAmountMerchantModel:merchantModel type:@"freeze"];
            } else if([subtitle containsString:@"金额解冻"]){
                [self transferAmountMerchantModel:merchantModel type:@"unfreeze"];
            }
            
        });
  
        
    }];
}

/**商户审核*/
- (void)audiMerchantModel:(PMMerchantManagerModel *)merchantModel{
   
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeMerchantAudit withTitle:@"商户审核" message:@"审核状态" cancel:@"取消" sure:@"确定" objectDict:nil cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] initWithDictionary:object];
        dataDictionary[@"merchantId"] = merchantModel.modelid;
        [self.viewModel auditMerchantInfo:dataDictionary];
    }];
    
    
}

/**禁用/启用*/
- (void)disableMerchantModel:(PMMerchantManagerModel *)merchantModel{
   
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeTipAlter withTitle:@"启用或者禁用商户" message:@"确认要启用或者禁用选择的商户?" cancel:@"取消" sure:@"确定" objectDict:nil cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] init];
        dataDictionary[@"merchant_ids"] = merchantModel.modelid;
        [self.viewModel disableMerchantInfo:dataDictionary];
    }];
    
    
}

/**删除*/
- (void)deleteMerchantModel:(PMMerchantManagerModel *)merchantModel{
   
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeTipAlter withTitle:@"删除商户" message:@"确认要删除选择的商户?" cancel:@"取消" sure:@"确定" objectDict:nil cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] init];
        dataDictionary[@"merchant_id"] = merchantModel.modelid;
        [self.viewModel deleteMerchantInfo:dataDictionary];
    }];
}

///更新余额
- (void)updateAmountMerchantModel:(PMMerchantManagerModel *)merchantModel{
    NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] init];
    dataDictionary[@"merchant_id"] = merchantModel.modelid;
    [self.viewModel updateAmountMerchantInfo:dataDictionary];
}


///余额扣划 //  余额冻结 //  金额解冻
- (void)transferAmountMerchantModel:(PMMerchantManagerModel *)merchantModel type:(NSString *)type{
    
    NSString *title = @"";
    NSString *message = @"";
    NSDictionary *dict = @{};

    if([type isEqualToString:@"deduct"]){
        title = @"商户划扣金额";
        message = [NSString stringWithFormat:@"%@ %@ 元",@"可用余额",merchantModel.amount_useable];
        dict = @{@"subTitles":@[@"扣划金额"]};
    } else if ([type isEqualToString:@"freeze"]){
        title = @"商户余额冻结";
        message = [NSString stringWithFormat:@"%@ %@ 元",@"可用余额",merchantModel.amount_useable];
        dict = @{@"subTitles":@[@"冻结金额"]};

    } else if ([type isEqualToString:@"unfreeze"]){
        message = [NSString stringWithFormat:@"%@ %@ 元",@"可用冻结余额",merchantModel.amount_freeze];
        title = @"商户金额解冻";
        dict = @{@"subTitles":@[@"解冻金额"]};
    }
    
    @weakify(self);
    [LZToolView showAlertType:LZAlertTypeAmountDeducted withTitle:title message:message cancel:@"取消" sure:@"确定" objectDict:dict cancelBlock:^(id  _Nullable object) {} sureBlock:^(id  _Nullable object) {
        @strongify(self);
        NSMutableDictionary *dataDictionary = [[NSMutableDictionary alloc] init];
        dataDictionary[@"merchant_id"] = merchantModel.modelid?:@"";
        dataDictionary[@"amount"] = object?:@"";
        dataDictionary[@"type"] = type?:@"";
        [self.viewModel transferAmountMerchantInfo:dataDictionary];
    }];
   
}




- (LZTableSlideView *)tableView{
    if(!_tableView){
        _tableView = [[LZTableSlideView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, K_SCREENHEIGHT - 50)];
    }
    return _tableView;
}


@end
